﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Text.RegularExpressions;

namespace CueMounter {
	public class AuCDTectProcess {
		public string File { get; private set; }
		private Process process;
		private Regex resultRegex = new Regex("^This track looks like (?<Type>MPEG|CDDA) with probability (?<Probability>[0-9]+)%$");
		private bool matched = false;

		public AuCDTectProcess(string file) {
			File = file;
			process = new Process();
			process.StartInfo.CreateNoWindow = true;
			process.StartInfo.FileName = "AuCDTect.exe";
			process.StartInfo.Arguments = "-m10 \"" + file + "\"";
			process.StartInfo.UseShellExecute = false;
			process.StartInfo.RedirectStandardOutput = true;
			process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
			process.EnableRaisingEvents = true;
		}

		void process_OutputDataReceived(object sender, DataReceivedEventArgs e) {
			if(e.Data == null) {
				if(!matched) {
					OnCompleted(false, "Error", -1);
				}
				return;
			}
			Match match = resultRegex.Match(e.Data);
			if(match.Success) {
				string type = match.Groups["Type"].Value;
				int probability = int.Parse(match.Groups["Probability"].Value);
				matched = true;
				OnCompleted(true, type, probability);
			}
		}

		public void Start() {
			process.Start();
			process.BeginOutputReadLine();
		}

		public event EventHandler<AuCDTectCompleteEventArgs> Completed;
		private void OnCompleted(bool success, string type, int probability) {
			if(Completed != null) {
				Completed(this, new AuCDTectCompleteEventArgs(success, type, probability));
			}
		}
	}

	public class AuCDTectCompleteEventArgs : EventArgs {
		public bool Success { get; private set; }
		public string Type { get; private set; }
		public int Probability { get; private set; }

		public AuCDTectCompleteEventArgs(bool success, string type, int probability) {
			Success = success;
			Type = type;
			Probability = probability;
		}
	}
}
